package com.kpi.web;

import Authorization.User;
import Authorization.UserController;
import Levels.Level;
import Session.SessionHelper;
import Session.TestSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Controller
public class FirstController {
    private UserController userController;
    private TestSession userTestSession = null;
    private User loggedUser;
    private int onLevel;
    public FirstController() {
        userController = new UserController();
    }


    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        request.setAttribute("invalid_log_or_pass", "");
        try {
            request.setCharacterEncoding("UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  // записать в лог
        }
        return "index";
    }

    /**
     * Обрабатываем звпрос нажатия на кнопку - логин
     *
     * @param request
     * @return
     */

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String onClickLoginButton(HttpServletRequest request, String login, String password, HttpServletResponse response) {
        User userToCheck = new User(login, password);
        if (userController.hasSuccessfullyLogged(userToCheck)) {
            if (isAdmin(userToCheck)) {
                createAdminRequest(request,userToCheck);
                return "adminpage";
            } else {
                loggedUser=userToCheck;
                request.removeAttribute("login");
                request.removeAttribute("password");
                createUserTestSession(userToCheck);
                createTestingRequest(request);
                return "question";
            }
        } else {
            request.setAttribute("invalid_log_or_pass", "This login or password is incorrect, please try again or register");
            return "index";
        }
    }



    /**
     * Здесь все ок
     *
     * @return
     */
    @RequestMapping(value = "/register/", method = RequestMethod.GET)
    public String onClickRegisterButton() {
        return "registration";
    }

    @RequestMapping(value = "/register/", method = RequestMethod.POST)
    public String onClickInRegister(HttpServletRequest request, String newLogin, String newPassword, HttpServletResponse response) {
        if(newLogin.equals("")||newPassword.equals("")){
            createEmptyLoginError(request);
            return "registration";
        }

        if (userController.isAlreadyLoginExists(newLogin)) {
            request.setAttribute("login_already_exists", "This login already exists,<br>please enter new login...");
            return "registration";
        } else {
            loggedUser=new User(newLogin,newPassword);
            userController.createNewUser(loggedUser);

            createUserTestSession(loggedUser);
            createTestingRequest(request);
            return "question";
        }
    }

    @RequestMapping(value = "/process/", method = RequestMethod.POST)
    public String onClickAnswerButton(HttpServletRequest request ,String userAnswer) {
      userTestSession.setAnswer(userAnswer);
       userTestSession.nextQuestion();
        return getTestStepResult(request);

    }

    private String getTestStepResult(HttpServletRequest request) {
        if(!userTestSession.hasNextInLevel()){
            onLevelEnding();
        }
        if(userTestSession.isEnd()){
            createUserResults(request);
            return "userresult";
        } else {
            createTestingRequest(request);
            return "question";
        }
    }

    private void onLevelEnding() {
        int levelPoints = userTestSession.countCorrect();
        if(levelPoints>=3){
            userTestSession.addSessionPoints(levelPoints);
            userTestSession.flushAnswers();
            userTestSession.levelUp();
            if(!userTestSession.isEnd())
            onLevel+=Level.ONE.getCountPerLevel();
        } else {
            userTestSession.flushAnswers();
            userTestSession.refreshLevel();
        }
    }

    @RequestMapping(value = "/next/", method = RequestMethod.GET)
    public String onClickNextButton(HttpServletRequest request) {
        userTestSession.setAnswer(" ");
        userTestSession.nextQuestion();
        return getTestStepResult(request);
    }

    @RequestMapping(value = "/prev/", method = RequestMethod.GET)
    public String onClickPrevButton(HttpServletRequest request) {
        userTestSession.previousQuestion();
        createTestingRequest(request);
        return "question";
    }

    @RequestMapping(value = "/exit/", method = RequestMethod.GET)
    public String onClickExitButton(HttpServletRequest request) {
        SessionHelper helper = new SessionHelper();
        helper.save(loggedUser,userTestSession);
        request.setAttribute("invalid_log_or_pass","Session was saved! Come back:)");
        return "index";
    }

    private void createTestingRequest(HttpServletRequest request) {

        request.setAttribute("count_from",onLevel+userTestSession.getCurrentIndexOfLevel()+1+"/"+userTestSession.totalQuestions());
        request.setAttribute("question", userTestSession.getQuestion().getStringQuestion());
        request.setAttribute("variants", userTestSession.getQuestion().getVariants());
    }

    private void createUserTestSession(User user){
        if(userTestSession==null)
        this.userTestSession=new SessionHelper().getSession(user);
    }

    /**
     * Проверочка на администратора
     *
     * @param user зарегистрированный
     * @return админ или нет
     */
    private boolean isAdmin(User user) {
        return user.getLogin().equals("admin");
    }

    private void createUserResults(HttpServletRequest request){
        request.setAttribute("userResult",userTestSession.getSessionPoints());
        request.setAttribute("totalResult",userTestSession.totalQuestions());
    }

    private void createAdminRequest(HttpServletRequest request, User admin){
        request.setAttribute("adminInfo",userController.getAdminInfo(admin));
    }

    private void createEmptyLoginError(HttpServletRequest request){
        request.setAttribute("login_already_exists","You entered empty login or pass, please enter valid data<br>for registration");
    }
}
